package com.atguigu.service.impl;


import com.alibaba.fastjson.JSON;
import com.atguigu.base.BaseMapper;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.entity.Dict;
import com.atguigu.mapper.DictMapper;
import com.atguigu.service.DictService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisException;

import java.util.*;

@Service
public class DictServiceImpl extends BaseServiceImpl<Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private JedisPool jedisPool;

    @Override
    public BaseMapper<Dict> getBaseMapper() {
        return dictMapper;
    }

    @Override
    public List<Map<String, Object>> findZnodesByParentId(Long id) {
        List<Map<String, Object>> zNodes = new ArrayList<>();
        List<Dict> dictList = findListByParentId(id);
        if (dictList == null || dictList.isEmpty()) {
            return zNodes;
        }
        for (int i = 0; i < dictList.size(); i++) {
            Map<String, Object> zNode = new HashMap<>();
            zNode.put("id", dictList.get(i).getId());
            zNode.put("name", dictList.get(i).getName());
            zNode.put("isParent", dictMapper.countByParentId(dictList.get(i).getId()) > 0);
            zNodes.add(zNode);
        }

        return zNodes;
    }

    @Override
    public List<Dict> findDictListByParentDictCode(String parentDictCode) {
        return dictMapper.findDictListByParentDictCode(parentDictCode);
    }
    @Override
    public List<Dict> findDictListByParentId(Long parentId) {
        return findListByParentId(parentId);
    }

    @Override
    public List<Dict> findDictListByDictCode(String dictCode) {
        Long parentId = dictMapper.getIdByCode(dictCode);

        return findListByParentId(parentId);
    }

    private List<Dict> findListByParentId(Long parentId) {
        try (Jedis jedis = jedisPool.getResource()) {
            String key = "shf:dict:parentid:" + parentId;
            String jsonStr = jedis.get(key);
            if (null!= jsonStr) {
                List<Dict> dictList = JSON.parseArray(jsonStr, Dict.class);
                return dictList;
            }

            // redis没有需要的数据，查数据库
            List<Dict> dictList = dictMapper.findListByParentId(parentId);
            jedis.set(key, JSON.toJSONString(dictList));

            return dictList;
        } catch (JedisException e) {
            // 可以在这里添加针对Jedis操作异常的处理逻辑，比如记录日志等
            e.printStackTrace();
            return Collections.emptyList();
        }
    }
}
